/*******************************************************************************
 * RegistrationAction.java
 *
 * Created by Nishan
 * Last modified Date: Oct 8, 2008 10:15:49 AM by nishan
  * Version : 0.1
 * Copyright (c) 2008 - 2009 cyberThink Infotech Pvt. Ltd., All rights reserved.
 ******************************************************************************/

package com.printeverywhere.action;

import static com.printeverywhere.util.LinksConstants.ADMIN_EDIT_PROFILE;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ValidationAware;
import com.printeverywhere.delegator.CommonFunctionDelegator;
import com.printeverywhere.delegator.LocationCategoriesServiceDelegator;
import com.printeverywhere.delegator.TranslationSystemServiceDelegator;
import com.printeverywhere.delegator.UserServiceDelegator;
import com.printeverywhere.dto.DateFormat;
import com.printeverywhere.dto.Languages;
import com.printeverywhere.dto.LocationCategories;
import com.printeverywhere.dto.NumberFormat;
import com.printeverywhere.dto.Timezones;
import com.printeverywhere.dto.User;
import com.printeverywhere.util.AdminConstants;
import com.printeverywhere.util.AttributeConstants;
import com.printeverywhere.util.CommonUtil;
import com.printeverywhere.util.SearchCriteria;
import com.printeverywhere.util.SearchListCriteria;

// TODO: Auto-generated Javadoc
/**
 * The Class RegistrationAction.
 */
public class RegistrationAction extends FrontBaseSupport implements
		ValidationAware, ServletRequestAware {

	/**
	 * Instantiates a new registration action.
	 */
	public RegistrationAction() {
		super(false, false);
	}

	/** Logger for this class. */
	private static final Logger logger = Logger.getLogger(RegistrationAction.class);

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The action. */
	private String action;

	/** The terms. */
	private Boolean terms;

	/** The referal. */
	private String referal;

	/** The request. */
	private HttpServletRequest request;

	/** The confirm passowrd. */
	private String confirmPassword;

	/** The user id. */
	private Integer userId;

	/** The timezone id. */
	private Integer timezoneId;

	/** The search list criteria. */
	private SearchListCriteria searchListCriteria = new SearchListCriteria();

	/** The user. */
	private User user;

	/** The numberFormat list. */
	private List<NumberFormat> numberFormatList = UserServiceDelegator
			.getNumberFormatList();

	/** The language list. */
	private List<Languages> languageList = TranslationSystemServiceDelegator
			.getList();

	/** The dateFormat list. */
	private List<DateFormat> dateFormatList = UserServiceDelegator
			.getDateFormatList();

	/** The region list. */
	private List<LocationCategories> regionList = getRegionListByLevel();

	/** The state list. */
	private List<LocationCategories> countryList = new ArrayList<LocationCategories>();

	/** The timezone list. */
	private List<Timezones> timezoneList = UserServiceDelegator
			.getTimezoneList();

	/** The state list. */
	private List<LocationCategories> stateList = new ArrayList<LocationCategories>();

	/**
	 * Gets the country list by level.
	 *
	 * @return the country list by level
	 */
	public List<LocationCategories> getRegionListByLevel() {
		searchListCriteria.removeAllAttribute();
		searchListCriteria.setAsc(true);
		searchListCriteria.setOrderBy(AdminConstants.CATEGORYNAME);
		searchListCriteria.setAttribute(AdminConstants.LEVEL, new Object[] {
		AdminConstants.ONE_NUMBER, searchListCriteria.EQ });
		return LocationCategoriesServiceDelegator.getList(searchListCriteria);
	}

	/**
	 * Populate registration form.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String populateRegistrationForm() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("populateRegistrationForm() - start"); //$NON-NLS-1$
		}

		action = "submitRegistrationForm.htm";

		SearchCriteria searchCriteria = new SearchCriteria();
		String countryCode=null;
		try{
			countryCode= CommonUtil.getCountryCodeByIP(request.getRemoteAddr());
		}catch (Exception e) {
			countryCode = "US";
		}
		if(countryCode.equals("XX"))countryCode = "US";

		timezoneId = UserServiceDelegator.getTimeZoneId(countryCode);

		if (this.request.getParameter(AttributeConstants.REFERAL) != null) {
			this.referal = this.request.getParameter(AttributeConstants.REFERAL);
		}

		if (logger.isDebugEnabled()) {
			logger.debug("populateRegistrationForm() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	/**
	 * Submit registration.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String submitRegistration() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("submitRegistration() - start"); //$NON-NLS-1$
		}

		String captchaId = request.getSession().getAttribute(
				nl.captcha.servlet.Constants.SIMPLE_CAPCHA_SESSION_KEY)
				.toString();
		// retrieve the response
		String captchaResponse = request
				.getParameter(AttributeConstants.CAPTCHA);

		if(terms == false){
			addActionError("Please Accept Tearms and Condition");
			return INPUT;
		}

		if (UserServiceDelegator.getUserByEmail(user.getEmail()) != null) {
			addActionError("User is registered with this Email Id Please try another");
			return INPUT;
		}

		if (UserServiceDelegator.getUserByUserId(user.getUserId()) == null) {
			if (captchaId.equals(captchaResponse)) {
				if (user.getUserId() != null) {
					if (this.referal != null
							&& this.referal.trim().length() > 0) {
						user.setUser(UserServiceDelegator.getUser(Integer
								.parseInt(CommonUtil.decrypt(this.referal))));
					}
					UserServiceDelegator.insertUser(user);

					if (logger.isDebugEnabled()) {
						logger.debug("submitRegistration() - end"); //$NON-NLS-1$
					}
					addActionMessage("Registration has been completed successfully");
					return SUCCESS;
				} else if (getActionErrors().size() > 0) {
					if (logger.isDebugEnabled()) {
						logger.debug("submitRegistration() - end"); //$NON-NLS-1$
					}
					return ERROR;
				} else {
					if (logger.isDebugEnabled()) {
						logger.debug("submitRegistration() - end"); //$NON-NLS-1$
					}
					return INPUT;
				}
			} else {
				if (logger.isDebugEnabled()) {
					logger.debug("submitRegistration() - end"); //$NON-NLS-1$
				}
				addActionError("Enter Valid Character for Captch Image");
				return INPUT;
			}
		} else {
			addActionError("User Id is already registered...");
			return INPUT;
		}
	}

	/**
	 * Edits the registration information.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String updateRegistrationInformation() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("updateRegistrationInformation() - start"); //$NON-NLS-1$
		}

		setLeftAllowed(true);
		setMyAccount(true);
		user.setActive(((User) request.getSession().getAttribute(AttributeConstants.USER)).getActive());
		UserServiceDelegator.updateUser(user);
		SearchCriteria searchCriteria = new SearchCriteria();
		searchCriteria.setAttribute(AttributeConstants.ID, user.getId());
		user = UserServiceDelegator.getList(searchCriteria).size() > 0?UserServiceDelegator.getList(searchCriteria).get(0): new User();
		request.getSession().setAttribute(AttributeConstants.USER, user);

		if (logger.isDebugEnabled()) {
			logger.debug("updateRegistrationInformation() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Update registration information.
	 *
	 * @return the string
	 *
	 * @throws Exception the exception
	 */
	public String editRegistrationInformation() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("editRegistrationInformation() - start"); //$NON-NLS-1$
		}

		setLeftAllowed(true);
		setMyAccount(true);
		action = "updateRegistrationForm.htm";
		user = (User) request.getSession()
				.getAttribute(AttributeConstants.USER);
		countryList = LocationCategoriesServiceDelegator.getCountryListByRegionId(user.getRegion().getCategoryId());
		stateList = LocationCategoriesServiceDelegator.getStateListByCountryId(user.getCountry().getCategoryId());

		if (logger.isDebugEnabled()) {
			logger.debug("editRegistrationInformation() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Gets the user information.
	 *
	 * @return the user information
	 *
	 * @throws Exception the exception
	 *
	 * @author ankur
	 *
	 * Gets the user information.
	 */
	public String getUserInformation() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("getUserInformation() - start"); //$NON-NLS-1$
		}

		action = ADMIN_EDIT_PROFILE;
		user = UserServiceDelegator.getUser(this.userId);
		countryList = LocationCategoriesServiceDelegator.getCountryListByRegionId(user.getRegion().getCategoryId());
		stateList = LocationCategoriesServiceDelegator.getStateListByCountryId(user.getCountry().getCategoryId());

		if (logger.isDebugEnabled()) {
			logger.debug("getUserInformation() - end"); //$NON-NLS-1$
		}
		return SUCCESS;
	}

	/**
	 * Gets the user.
	 *
	 * @return the user
	 */
	public User getUser() {
		return user;
	}

	/**
	 * Sets the user.
	 *
	 * @param user the new user
	 */
	public void setUser(User user) {
		this.user = user;
	}

	/**
	 * Gets the country list.
	 *
	 * @return the country list
	 */
	public List<LocationCategories> getCountryList() {
		return countryList;
	}

	/**
	 * Gets the state list.
	 *
	 * @return the state list
	 */
	public List<LocationCategories> getStateList() {
		return stateList;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see com.opensymphony.xwork2.ActionSupport#validate()
	 */
	@Override
	public void validate() {
		if (logger.isDebugEnabled()) {
			logger.debug("validate() - start"); //$NON-NLS-1$
		}

		if (request.getSession().getAttribute(AttributeConstants.USER) != null){
			setLeftAllowed(true);
			setMyAccount(true);
			action = "updateRegistrationForm.htm";
		}
		else
			action = "submitRegistrationForm.htm";
		super.validate();
		regionList = getRegionListByLevel();
		countryList = LocationCategoriesServiceDelegator.getCountryListByRegionId(Integer.parseInt(request.getParameter("user.region.categoryId")));
		stateList = LocationCategoriesServiceDelegator.getCountryListByRegionId(Integer.parseInt(request.getParameter("user.country.categoryId")));
		timezoneId = Integer.parseInt(request.getParameter("user.timezones.id"));

		if (logger.isDebugEnabled()) {
			logger.debug("validate() - end"); //$NON-NLS-1$
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.apache.struts2.interceptor.ServletRequestAware#setServletRequest(javax.servlet.http.HttpServletRequest)
	 */

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	/**
	 * Sets the country list.
	 *
	 * @param countryList the new country list
	 */
	public void setCountryList(List<LocationCategories> countryList) {
		this.countryList = countryList;
	}

	/**
	 * Sets the state list.
	 *
	 * @param stateList the new state list
	 */
	public void setStateList(List<LocationCategories> stateList) {
		this.stateList = stateList;
	}

	/**
	 * Gets the number format list.
	 *
	 * @return the number format list
	 */
	public List<NumberFormat> getNumberFormatList() {
		return numberFormatList;
	}

	/**
	 * Sets the number format list.
	 *
	 * @param numberFormatList the new number format list
	 */
	public void setNumberFormatList(List<NumberFormat> numberFormatList) {
		this.numberFormatList = numberFormatList;
	}

	/**
	 * Gets the date format list.
	 *
	 * @return the date format list
	 */
	public List<DateFormat> getDateFormatList() {
		return dateFormatList;
	}

	/**
	 * Sets the date format list.
	 *
	 * @param dateFormatList the new date format list
	 */
	public void setDateFormatList(List<DateFormat> dateFormatList) {
		this.dateFormatList = dateFormatList;
	}

	/**
	 * Gets the language list.
	 *
	 * @return the language list
	 */
	public List<Languages> getLanguageList() {
		return languageList;
	}

	/**
	 * Sets the language list.
	 *
	 * @param languageList the new language list
	 */
	public void setLanguageList(List<Languages> languageList) {
		this.languageList = languageList;
	}

	/**
	 * Gets the timezone list.
	 *
	 * @return the timezone list
	 */
	public List<Timezones> getTimezoneList() {
		return timezoneList;
	}

	/**
	 * Sets the timezone list.
	 *
	 * @param timezoneList the new timezone list
	 */
	public void setTimezoneList(List<Timezones> timezoneList) {
		this.timezoneList = timezoneList;
	}

	/**
	 * Gets the action.
	 *
	 * @return the action
	 */
	public String getAction() {
		return action;
	}

	/**
	 * Sets the action.
	 *
	 * @param action the new action
	 */
	public void setAction(String action) {
		this.action = action;
	}

	/**
	 * Gets the confirm password.
	 *
	 * @return the confirm password
	 */
	public String getConfirmPassword() {
		return confirmPassword;
	}

	/**
	 * Sets the confirm password.
	 *
	 * @param confirmPassword the new confirm password
	 */
	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	/**
	 * Gets the user id.
	 *
	 * @return the user id
	 */
	public Integer getUserId() {
		return userId;
	}

	/**
	 * Sets the user id.
	 *
	 * @param userId the new user id
	 */
	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	/**
	 * Gets the referal.
	 *
	 * @return the referal
	 */
	public String getReferal() {
		return referal;
	}

	/**
	 * Sets the referal.
	 *
	 * @param referal the new referal
	 */
	public void setReferal(String referal) {
		this.referal = referal;
	}

	/**
	 * Gets the timezone id.
	 *
	 * @return the timezone id
	 */
	public Integer getTimezoneId() {
		return timezoneId;
	}

	/**
	 * Sets the timezone id.
	 *
	 * @param timezoneId the new timezone id
	 */
	public void setTimezoneId(Integer timezoneId) {
		this.timezoneId = timezoneId;
	}

	/**
	 * @return the terms
	 */
	public Boolean getTerms() {
		return terms;
	}

	/**
	 * @param terms the terms to set
	 */
	public void setTerms(Boolean terms) {
		this.terms = terms;
	}

	/**
	 * @return the regionList
	 */
	public List<LocationCategories> getRegionList() {
		return regionList;
	}

	/**
	 * @param regionList the regionList to set
	 */
	public void setRegionList(List<LocationCategories> regionList) {
		this.regionList = regionList;
	}
}